package com.neulogistics.contrib.transfercenter.api.application.rpc;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.neulogistics.contrib.transfercenter.api.application.rpc.dto.CreateTaskOrderDTO;
import com.neulogistics.contrib.transfercenter.api.application.rpc.dto.WarehouseDTO;
import com.neulogistics.contrib.transfercenter.domain.model.valueobject.Address;
import com.neulogistics.infrastructure.common.rpc.client.SubstationClient;
import com.neulogistics.infrastructure.common.rpc.client.WarehouseClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TransferCenterRPC implements ITransferCenterRPC {
    @Resource
    WarehouseClient warehouseClient;

    @Resource
    IGeographyService geographyService;

    @Resource
    SubstationClient substationClient;

    @Override
    public Map<String, Integer> getRecommendedWarehouse(Address address) {
        // todo 处理服务可靠性
        // 远程调用，获取收货地址附近的中心库房和分站库房信息
        Map<String, JSONArray> data = warehouseClient.getRecommendedWarehouse(address).getData();
        List<WarehouseDTO> centerWarehouse = JSONUtil.toList(data.get("center"), WarehouseDTO.class);
        List<WarehouseDTO> subWarehouse = JSONUtil.toList(data.get("substation"), WarehouseDTO.class);

        HashMap<String, Integer> result = new HashMap<>();

        // 利用三方api得出最近的中心库房和分站库房id
        List<String> origins = centerWarehouse.stream()
                .map(p -> p.getWarehouseAddress().getLocation())
                .collect(Collectors.toList());
        String destination = geographyService.getLocation(address);
        Integer centerIndex = geographyService.getShortestDistanceIndex(origins, destination);
        result.put("center", centerWarehouse.get(centerIndex).getWarehouseId());

        origins = subWarehouse.stream()
                .map(p -> p.getWarehouseAddress().getLocation())
                .collect(Collectors.toList());
        Integer subIndex = geographyService.getShortestDistanceIndex(origins, destination);
        result.put("substation", subWarehouse.get(subIndex).getWarehouseId());

        // 返回结果
        return result;
    }

    @Override
    public Long createTaskOrder(CreateTaskOrderDTO createTaskOrderDTO) {
        String taskIdString = substationClient.createTaskOrder(JSONUtil.parseObj(createTaskOrderDTO)).getData();
        Long taskId = Long.valueOf(taskIdString);
        return taskId;
    }
}
